package com.itchu.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchu.common.domain.PageResult;
import com.itchu.common.exption.ExceptionEnum;
import com.itchu.common.exption.MusicException;
import com.itchu.system.domain.Singer;
import com.itchu.system.domain.Song;
import com.itchu.system.mapper.SingerMapper;
import com.itchu.system.mapper.SongMapper;
import com.itchu.system.service.SingerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.*;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SingerServiceImpl implements SingerService {

    @Autowired
    private SingerMapper singerMapper;

    @Autowired
    private SongMapper songMapper;

    /**
     * 查找歌手的分页信息
     * @param key   搜索条件
     * @param page  当前页
     * @param rows  页大小
     * @param sortBy
     * @param desc
     * @return
     */
    @Override
    public PageResult<Singer> findByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {


        //开启分页
        PageHelper.startPage(page,rows);
        //创建一个封装条件的对象
        Example example = new Example(Singer.class);
        if (!StringUtils.isEmpty(key)) {
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name","%" + key + "%");
            criteria.orLike("id","%" + key + "%");
        }
        if (!StringUtils.isEmpty(sortBy)) {
            example.setOrderByClause(sortBy+" "+(desc ? "desc" : "asc"));
        }
        List<Singer> singers = singerMapper.selectByExample(example);
        PageInfo<Singer> pageInfo = new PageInfo<>(singers);
        Get_Visit_Count();
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),singers);
    }

    /**
     * 添加歌手操作
     * @param singer
     * @return
     */
    @Override
    public void addSinger(Singer singer) {
        if (singer != null) {
            singer.setCreateTime(new Date());
            singer.setUpdateTime(new Date());
            singerMapper.insertSelective(singer);
        }
    }

    /**
     * 更新歌手操作
     * @param singer
     * @return
     */
    @Override
    public void updateSinger(Singer singer) {
        if (singer != null) {
            singer.setUpdateTime(new Date());
            singerMapper.updateByPrimaryKey(singer);
        }
    }

    /**
     * 删除歌手操作
     * @param id  歌手id
     * @return
     */
    @Override
    public void deletSinger(Long id) {
        singerMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据歌手id查出所有歌曲
     * @param id  歌手id
     * @return
     */
    @Override
    public List<Song> findSongsBySingerId(Long id) {
        Song song = new Song();
        song.setSingerId(id);
        List<Song> list = songMapper.select(song);
        List<Singer> singers = singerMapper.selectAll();
        list.stream().forEach(s -> {
            singers.stream().forEach(singer -> {
                if (s.getSingerId().equals(singer.getId())) {
                    s.setSinger(singer);
                }
            });
        });
        return list;
    }

    /**
     * 查找所有歌手
     * @return
     */
    @Override
    public List<Singer> findAll() {
        return singerMapper.selectAll();
    }

    /**
     * 按名字做模糊搜索
     * @param name
     * @return
     */
    @Override
    public List<Singer> searchSingersByName(String name) {
        Example example = new Example(Singer.class);
        example.createCriteria().andLike("name","%"+name+"%");
        List<Singer> list = singerMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(list)) {
            throw new MusicException(ExceptionEnum.MUSIC_NOT_SONGS);
        }
        return list;
    }

    /*
     * 获取txt文件中的数字，即之前的访问量
     * 传入参数为： 字符串: txtFilePath,文件的绝对路径
     */
    public static Long Get_Visit_Count() {


        try {
            ClassPathResource classPathResource = new ClassPathResource("counter.txt");
            InputStream inputStream = classPathResource.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            //循环读取数据
            String str = null;
            StringBuffer content = new StringBuffer();
            while ((str = in.readLine()) != null) {
                content.append(str);
            }
            //关闭流
            in.close();

            //System.out.println(content);
            // 解析获取的数据
            Long count = Long.valueOf(content.toString());
            count ++; // 访问量加1
            //写入相应的文件
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(classPathResource.getFile()),"UTF-8"));
            out.write(String.valueOf(count));

            //清楚缓存
            out.flush();
            //关闭流
            out.close();

            return count;
        }
        catch (Exception e){
            e.printStackTrace();
            return 0L;
        }
    }
}